package gui.parta;

import java.nio.charset.StandardCharsets;

/**
 *
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
public class DataPacket {
    public static void main(String[] args) {
        System.out.println(DataPacket.stringToHex("123A"));
        System.out.println(DataPacket.convertToDataPacket("123A"));
        System.out.println(DataPacket.getDataFromDataPacket("AA04313233417BD7BB"));
    }

    // 字符串转十六进制
    public static String stringToHex(String str) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            int ch = str.charAt(i);
            String s4 = Integer.toHexString(ch);
            res.append(s4);
        }
        return res.toString();
    }

    // 转换成数据包
    public static String convertToDataPacket(String data) {
        // 数据包 = 头，数据长度，数据段，CRC代码和尾巴
        String len = data.length() > 10 ? data.length() + "" : "0" + data.length();
        String dataSegment = stringToHex(data);
        String crc = CRC16.getCRC(data.getBytes(StandardCharsets.UTF_8));
        return "AA" + len + dataSegment + crc + "BB";
    }

    public static String getDataFromDataPacket(String hexData) {
        if (hexData.length() < 10) {
            throw new IllegalArgumentException("非法数据包！");
        }
        String s = hexData.substring(4, hexData.length() - 6);
        return CRC16.hexStringToString(s);
    }
}
